package com.wuseguang.springcloud.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class PinYinUtils {

    private static Logger logger = LoggerFactory.getLogger(PinYinUtils.class);

    /**
     * @描述 汉字转拼音
     * @创建人 zm
     * @创建时间 2020/5/25
     */
    public static String getFullSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("getFullSpell,erorr={}", e);
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }


    public static List<TreeMap<String, Object>> px(List<Map<String, Object>> list, String parm) {
        logger.info("list={}",list.toString());
        List<TreeMap<String, Object>> lists = new ArrayList<TreeMap<String, Object>>();
        for (int i = 1; i <= 26; i++) {
            TreeMap<String, Object> map = new TreeMap<>();
            String word = String.valueOf((char) (96 + i)).toUpperCase();
            List<Map<String, Object>> letter = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> stringObjectMap : list) {
                logger.info("student_name,px={}",stringObjectMap.get(parm));
                String student_name = getFullSpell(stringObjectMap.get(parm).toString()).substring(0, 1);
                if (word.equals(student_name)) {
                    letter.add(stringObjectMap);
                }
            }
            if (letter != null && letter.size() > 0) {//去空
                map.put("letter", word);
                map.put("list", letter);
                lists.add(map);
            }
        }
        return lists;
    }
}
